import pickle
import os
from flask import make_response
from flask import Flask, request, render_template, jsonify, Response, json
from pymongo import MongoClient
from functools import wraps
app = Flask(__name__)
#client = MongoClient("mongodb://127.0.0.1:27017")
client = MongoClient("mongodb://127.0.0.1:27039")
db = client['local']

def allow_cross_domain(fun):
    @wraps(fun)
    def wrapper_fun(*args, **kwargs):
        rst = make_response(fun(*args, **kwargs))
        rst.headers['Access-Control-Allow-Origin'] = '*'
        rst.headers['Access-Control-Allow-Methods'] = 'PUT,GET,POST,DELETE'
        allow_headers ="Referer,Accept,Origin,User-Agent"
        rst.headers['Access-Control-Allow-Headers'] = allow_headers
        return rst
    return wrapper_fun

@app.route('/GetTree/', methods = ['GET'])
@allow_cross_domain
def getTree():
    the_ID = str(request.values['target'])
    print(the_ID)
    cursor = db.tree.find({'rootid': the_ID})
    result = None
    for one in cursor:
        result = one
        break
    print("haha")
    if result == None:
        return "ERROR"
    return json.dumps(result['tree'])

@app.route('/GetCluster/', methods = ['GET'])
@allow_cross_domain
def getCluster():
    page_size = int(request.values['page_size'])
    year = int(request.values['year'])
    rootID_clusters_selectedCluster = str(request.values['target'])
    print("Handling: " + rootID_clusters_selectedCluster)
    rootID = rootID_clusters_selectedCluster.split('_')[0]
    clusters = rootID_clusters_selectedCluster.split('_')[1]
    selected = rootID_clusters_selectedCluster.split('_')[2]
    page = int(rootID_clusters_selectedCluster.split('_')[3])
    print("rootID: " + str(rootID))
    print("clusters: " + str(clusters))
    print("selected: " + str(selected))
    print("page: " + str(page))
    result = None
    cursor = db.cluster.find({'rootid': rootID, 'cluster_name': selected})
    for one in cursor:
        result = one
        break
    if result == None:
        return "ERROR"
    resultlist = list()
    for item in result['nodeTitles']:
        if year == 0 or year == item[3]:
            resultlist.append([item[0], item[1], item[2]])
    resultlist.sort(key = (lambda x: int(x[2])), reverse = True)
    # currently not separated into pages
    return json.dumps(resultlist)

@app.route('/GetNode/', methods = ['GET'])
@allow_cross_domain
def getNode():
    rootID_clusters_selectedCluster_selectedNode = str(request.values['target'])
    print("Handling: " + rootID_clusters_selectedCluster_selectedNode)
    rootID = rootID_clusters_selectedCluster_selectedNode.split('_')[0]
    clusters = rootID_clusters_selectedCluster_selectedNode.split('_')[1]
    selectedCluster = rootID_clusters_selectedCluster_selectedNode.split('_')[2]
    selectedNode = rootID_clusters_selectedCluster_selectedNode.split('_')[3]
    result = None
    cursor = db.node.find({'rootid': rootID, 
      'cluster': selectedCluster, 'id': selectedNode})
    for one in cursor:
        result = one
        break
    if result == None:
        return "ERROR"
    del result['cluster_count']
    del result['_id']
    return json.dumps(result)

@app.route('/InfluenceGraph/',methods=['GET'])
@allow_cross_domain
def get_graph_data():
    result=request.values
    name=str(result['id'])
    cursor = db.graph.find({'target': name})
    result = None
    for one in cursor:
        result = one
        break
    if result == None:
        return "ERROR"
    del result['_id']
    del result['target']
    return json.dumps(result)

if __name__ == '__main__':
    app.run('0.0.0.0', port = 5001)
